#!/bin/bash

###
### Program: timemachine
### File:    tm-offsite.sh
### Version: 2.0
### Owner:   raptus ag
### Author:  Florian S.
### Purpose:
###
### Send backup to an offsite location
### But no archiving is performed
###

#
# standard stuff
#

if ! test "$#" -eq 1
then
    echo "Usage: $0 <config-file>"
    exit 1
fi

ME=`basename $0 | head -c -4`

SCRIPT=$(readlink -f $0)
SCRIPTPATH=`dirname $SCRIPT`
OLDDIR="`pwd`"
cd $SCRIPTPATH

CONFIGFILE="$1"
if ! test -f "$CONFIGFILE"
then
    echo "ERROR: Cannot find config file $CONFIGFILE"
    exit 1
fi

source "../config/defaults.conf"
source "$CONFIGFILE"
source "functions/locking.inc.sh"
source "functions/logging.inc.sh"
source "functions/errorcodes.inc.sh"

echo "Offsite Debuglog `date`" > $DEBUGOFFSITE 2>&1

#
# logfile stuff
#

log "-----------------------------------------------------------------------"
log "This is $CUSTOMER $HOSTNAME timemachine offsite backup"
log "Config $CONFIGFILE, Job $JOBNAME"
lock upload
if [ $? == 1 ];
then
        log "ERROR: Lockfile present, exiting."
        log "- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -"
        send "error"
        exit 1
fi

REMOTEBASE="$MOUNTDIR/$OFFSITESRV/$HOSTNAME/$JOBNAME"

if test "$OFFSITETYPE" = "sftp"; then REMOTEDIR="$REMOTEBASE""$SFTPDIR/$HOSTNAME/$JOBNAME"; fi
if test "$OFFSITETYPE" = "nfs";  then REMOTEDIR="$REMOTEBASE/$HOSTNAME/$JOBNAME"; fi

if ! test -d $REMOTEBASE
then
    mkdir -p $REMOTEBASE >> $DEBUGOFFSITE 2>&1
fi

if test -z "$OFFSITESRV"
then
    log "ERROR: No sFTP-Server given. Please check your confg."
    log "- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -"
    send "error"
    unlock
    exit 1
fi


if ! test -d $BACKUPDIR/$CUSTOMER/upload/$HOSTNAME/$JOBNAME
then
    log "ERROR: Nothing found to upload. exiting."
    log "- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -"
    send "error"
    unlock
    exit 1
fi

if test "$OFFSITETYPE" = "sftp"; then 

    if test -z "`which sshfs`"
    then
        log "ERROR: SSHFS seems not to be installed. Please install SSHFS."
        log "- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -"
        send "error"
        unlock
        exit 1
    fi

    sshfs $SFTPUSR@$OFFSITESRV:/ $REMOTEBASE; 
fi


if test "$OFFSITETYPE" = "nfs";  then mount -t nfs $OFFSITESRV $REMOTEBASE; fi

if test -z "`mount | grep $OFFSITESRV`"
then
    log "ERROR in $OFFSITETYPE: Unable to mount remote sFTP server."
    log "- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -"
    send "error"
    unlock
    exit 1

else
    if test -d "$REMOTEDIR"
    then
        log "Sending most current backup to $OFFSITESRV:/upload/$HOSTNAME/$JOBNAME."

    else
        mkdir -p $REMOTEDIR >> $DEBUGOFFSITE 2>&1
        log "Initial Backup. Sending most current Backup to $OFFSITESRV:/upload/$HOSTNAME/$JOBNAME"
        log "ATTENTION: This can consume a hudge amout of time."
    fi

    OLDIFS=$IFS
    IFS=$'\n' 
    TOUPLOAD="`ls $BACKUPDIR/$CUSTOMER/upload/$HOSTNAME/$JOBNAME`"

    if test "$ONSITESPEED" = "0"
    then
        SPEED=""
        LOGSPEED=""
    else
        SPEED="--bwlimit=$ONSITESPEED"
        LOGSPEED="[limit: $ONSITESPEED KB/s]"
    fi


    MAILMESSAGE="success"
    for i in $TOUPLOAD
    do
        SRC=$BACKUPDIR/$CUSTOMER/upload/$HOSTNAME/$JOBNAME/$i
        DST=$REMOTEDIR
        
        EXCLUDE=""
        for j in "${EXCLUDE_LIST[@]}"
        do
            EXCLUDE="--exclude \"$j\" $EXCLUDE"
        done

        # rsync copy process
        # --archive         includes -r (recursive) -l (symlinks) -p (rights) -t (timestamps) -g (group) -o (owner) -D (special devices)
        # --delete-during   delete files not in source repo during copy process
        # --update          skip files that are newer on the receiver
        # --stats           show stats (necessary for speed output)
        # --verbose         verbose log (LOGFILEPATH/DEBUG/)
        # --human-readable  show stats in a human readable format

        if test -z "$RSYNCOFFSITE"; then RSYNCOFFSITE="-rlh --delete-during --update --stats --verbose -h"; fi

        if test -z "$NICELEVEL"; then NICELEVEL="18"; fi

        IFS=$OLDIFS
        STATS=`nice -n $NICELEVEL rsync $RSYNCOFFSITE $EXCLUDE $SPEED "$SRC" "$DST" | tee $DEBUGOFFSITE 2>&1`
        IFS=$'\n'
        F=`echo "$STATS" | tail -n 14 | grep "Total file size" | cut -d " " -f 4`
        T=`echo "$STATS" | tail -n 14 | grep "Total transferred file size" | cut -d " " -f 5`
        RET=$?

        # getting rsync error code
        rsync_status $RET
        log " --> $i finished. Status: $RSYNCMSG [Total: $F, Sent: $T] $LOGSPEED"

        if [[ "$RSYNCMSG" == *ERROR* ]]; then MAILMESSAGE="failed"; fi
    done
fi

#
# cleanup part
#

umount $REMOTEBASE >> $DEBUGOFFSITE 2>&1
rmdir -p $REMOTEBASE >> $DEBUGOFFSITE 2>&1

unlock upload
log "Backup done!"
log "-----------------------------------------------------------------------"

if [ "$OFFSITEMAIL" == "off" ]; then OFFSITEMAIL=""; fi

if ! test -z "$OFFSITEMAIL"; then send "$MAILMESSAGE"; fi

# eof
